package com.bite.system.service.sysuser.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.common.core.constants.HttpConstants;
import com.bite.common.core.domain.LoginUser;
import com.bite.common.core.domain.R;
import com.bite.common.core.domain.vo.LoginUserVO;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.enums.UserIdentity;
import com.bite.common.security.exception.ServiceException;
import com.bite.common.security.service.TokenService;
import com.bite.system.domain.sysuser.SysUser;
import com.bite.system.domain.sysuser.SysUserServerDTO;
import com.bite.system.mapper.sysuser.SysUserMapper;
import com.bite.system.service.sysuser.ISysUserService;
import com.bite.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
//当我们修改nacos中secret值的时候，加上这个注解，就不需要重新启动项目
@RefreshScope
public class SysUserServiceImpl implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Value("${jwt.secret}")
    private String secret;
    @Autowired
    private TokenService tokenService;
    @Override
    public R<String> login(String userAccount, String password) {
        //通过账号去数据库中查询
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        //select password from tb_test where user_account = #{userAccount}
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getUserId,SysUser::getPassword,SysUser::getNickName).eq(SysUser::getUserAccount,userAccount));
        R loginResult = new R();
        if(sysUser == null) {
            loginResult.setCode(0);
            loginResult.setMsg(ResultCode.AILED_USER_EXISTS.getMsg());
            return loginResult;
        }

        if(BCryptUtils.matchesPassword(password,sysUser.getPassword())){

            return R.ok(tokenService.createToken(sysUser.getUserId(),secret, UserIdentity.ADMIN.getValue(), sysUser.getNickName()));
        }
        loginResult.setCode(0);
        loginResult.setMsg("账号密码错误");
        return loginResult;
    }

    @Override
    public int add(SysUserServerDTO sysUserServerDTO) {
        //判断新增账号是否存在于数据库‘
        SysUser sysUser = new SysUser();
        List<SysUser> userList = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount,sysUserServerDTO.getUserAccount()));
        if(CollectionUtil.isNotEmpty(userList)){
            //用户已经存在
            //自定义异常
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);

        }
        sysUser.setUserAccount(sysUserServerDTO.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserServerDTO.getPassword()));
//        sysUser.setCreateBy(100L);//获取当前用户的id
//        sysUser.setCreateTime(LocalDateTime.now());利用mybatisPlus的自动填充

        return sysUserMapper.insert(sysUser);

    }

    @Override
    public R<LoginUser> info(String token) {
        token = d(token);
        LoginUser loginUser = tokenService.getLoginUser(token,secret);
        if(loginUser == null) {
            return R.fail();
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        return  R.ok(loginUser);
    }

    @Override
    public boolean logout(String token) {
        //解析token，将redis中的相关数据删除
        token = d(token);
        return tokenService.deleteLoginUser(token,secret);
    }
    private String d(String token){
        if (StrUtil.isNotEmpty(token) &&
                token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return token;
    }

}
